package com.zh.note.huawei.onehundred.阿里巴巴找黄金宝箱5;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * https://dream.blog.csdn.net/article/details/130963117
 */
public class Main {
    public static void main(String[] args) {
        // Scanner sc = new Scanner(System.in);
        // String s = sc.nextLine();
        // int target = sc.nextInt();
        int target = 4;
        String s = "2,10,-3,-8,40,5";
        // int target = 1;
        // String s = "8";

        int[] nums = Arrays.stream(s.split(",")).mapToInt(Integer::parseInt).toArray();
        int res = solution2(nums, target);
        System.out.println(res);
    }

    //暴力法
    private static int solution(int[] nums, int target) {

        int maxSum = Integer.MIN_VALUE;
        for (int i = 0; i <= nums.length - target; i++) {
            int sum = 0;
            for (int j = i; j < i + target; j++) {
                sum += nums[j];
            }
            if (sum > maxSum) {
                maxSum = sum;
            }
        }
        return maxSum;
    }

    private static int solution2(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();

        long[] prefixSum = new long[nums.length + 1];
        int start = 0;
        long maxSum = 0;
        for (int i = 0; i < nums.length; i++) {
            prefixSum[i + 1] = prefixSum[i] + nums[i];
            int frequency = map.getOrDefault(nums[i], 0);
            map.put(nums[i], frequency + 1);
            while (map.size() > target) {
                int startNum = nums[start];
                map.put(startNum, map.get(startNum) - 1);
                if (map.get(startNum) == 0) {
                    map.remove(startNum);
                }
                start++;
            }
            if (map.size() == target) {
                long sum = prefixSum[i + 1] - prefixSum[start];
                maxSum = Math.max(maxSum, sum);
            }
        }
        return (int) maxSum;
    }
}
